from . import *

from user.forms import RegisterForm, ChangePasswordForm, \
    ChangeUserForm
from user.views import commo


@require_POST
def user_register_view(request):
    """用户注册，默认密码为00_00_00
    group:1=管理员/2=车辆调度员
    """
    try:
        form = RegisterForm(json.loads(request.body))
        if form.is_valid():
            username = form.cleaned_data.get('user_name')
            job_num = form.cleaned_data.get('job_num')
            telephone = form.cleaned_data.get('tel')
            real_name = form.cleaned_data.get('real_name')
            department = form.cleaned_data.get('dep')
            group = int(form.cleaned_data.get('group'))
            user = User(user_name=username, job_num=job_num, tel=telephone,
                        real_name=real_name, dep=department, group=group)
            user.save()
            # 设置权限menu数据
            commo.user_set_menu_data(user=user, group=group)
            return restful.ok(message='注册成功！')
        else:
            errors = form.get_errors()
            return restful.server_error(message=errors)
    except Exception as e:
        # 返回异常堆栈信息到日志中,e是异常类
        log_print(waring=traceback.format_exc())
        return restful.server_error(message=RETURN_MESSAGE)


@require_POST
def user_login_view(request):
    """用户登陆验证"""
    try:
        username = json.loads(request.body)['username']
        password = json.loads(request.body)['password']
        user = User.objects.filter(user_name=username,
                                   status__in=[1, 3]).first()
        message = '用户不存在或者密码错误，请确认好重新输入！'
        if user:
            # 通过Bcrypt验证密码
            if tokens.validate_bcrypt_password(password, user.password):
                # 生成权限信息
                menu_data = commo.user_search_menu_data(user=user)
                # 生成头像资源
                dirname = os.path.join(STATIC_URL,
                                       str(user.icon).replace('\\', '/'))
                # 返回前端数据,绑定token
                userinfo = {'username': username,
                            'token': create_token(username),
                            'icon': dirname}
                data = {'user': userinfo, 'right': menu_data}
                return restful.ok(message='登陆成功！', data=data)
            else:
                return restful.server_error(message=message)
        else:
            return restful.server_error(message=message)
    except Exception as e:
        log_print(waring=traceback.format_exc())
        return restful.server_error(message=RETURN_MESSAGE)


@require_GET
def user_logout_view(request):
    """
    用户退出登陆
    """
    try:
        token = request.META.get('HTTP_AUTHORIZATION')
        user_name = get_username(token)
        # 清除后端token
        cache.set(user_name, token, 0)
        return restful.ok(message="当前用户已退出登陆！")
    except Exception as e:
        log_print(waring=traceback.format_exc())
        return restful.server_error(message=RETURN_MESSAGE)


@require_POST
def user_delete_view(request):
    """用户删除操作,status状态更新为'删除'->2"""
    try:
        user_id = json.loads(request.body)['id']
        User.objects.filter(pk=user_id).update(status=0)  # 用户删除
        return restful.ok(message="已删除当前用户！")
    except Exception as e:
        log_print(waring=traceback.format_exc())
        return restful.server_error(message=RETURN_MESSAGE)


@require_POST
def user_change_user(request):
    """用户改写操作"""
    try:
        form = ChangeUserForm(json.loads(request.body))
        if form.is_valid():
            user_id = json.loads(request.body)['id']
            group = int(form.cleaned_data.get('group'))  # 角色权限信息
            dep = json.loads(request.body)['dep']
            tel = json.loads(request.body)['tel']
            # 第一步：用户更新操作
            User.objects.filter(pk=user_id).update(dep=dep, tel=tel,
                                                   group=group)
            # 第二步：同步修改用户权限菜单信息
            user = User.objects.get(pk=user_id)
            commo.user_set_menu_data(user=user, group=group)
            return restful.ok(message="用户信息已修改！")
        else:
            errors = form.get_errors()
            return restful.params_error(message=errors)
    except Exception as e:
        log_print(waring=traceback.format_exc())
        return restful.server_error(message=RETURN_MESSAGE)


@require_POST
def user_change_password(request):
    """修改用户密码, 密码6-10位
    request参数:password_repeat, password
    """
    try:
        front_user = request.front_user
        form = ChangePasswordForm(json.loads(request.body))
        if form.is_valid():
            password = form.cleaned_data.get('password')
            # 更新密码
            front_user.password = tokens.set_bcrypt_password(password)
            front_user.save()
            return restful.ok(message='修改成功，新密码为{}！'.format(password))
        else:
            errors = form.get_errors()
            return restful.params_error(message=errors)
    except Exception as e:
        log_print(waring=traceback.format_exc())
        return restful.server_error(message=RETURN_MESSAGE)


@require_POST
def user_reset_password(request):
    """重置密码"""
    try:
        user_id = json.loads(request.body)['id']
        # 用户更新操作
        User.objects.filter(pk=user_id).update(
            password=tokens.set_bcrypt_password(USER_PASSWORD))
        return restful.ok(message="密码重置成功，新密码为{}".format(USER_PASSWORD))
    except Exception as e:
        log_print(waring=traceback.format_exc())
        return restful.server_error(message=RETURN_MESSAGE)


@require_POST
def user_upload_image(request):
    """用户头像更新"""
    try:
        # 通过FILE获取image
        icon = request.FILES.getlist('picFile')[0]
        # 获取用户对象
        user_obj = request.user_obj
        # 获取图片hash值
        hash = attachment2.get_ufn()
        # 重写文件名
        icon.name = hash + '.' + icon.name.rsplit('.')[-1]
        # 旧头像删除
        mysql_icon = str(user_obj.icon)
        icon_old_dir = os.path.join(USER_UPLOAD_TO, mysql_icon)
        if mysql_icon.endswith('newuser.png'):
            pass
        else:
            try:
                # 删除旧头像，默认的头像不会被删除
                os.remove(icon_old_dir)
            except:
                pass
        # 更新头像
        user_obj.icon = icon
        user_obj.save()
        # 重新获取头像,返回数据
        icon_change = os.path.join(STATIC_URL,
                                   str(user_obj.icon).replace('\\', '/'))
        return restful.ok(data=icon_change)
    except Exception as e:
        log_print(waring=traceback.format_exc())
        return restful.server_error(message=RETURN_MESSAGE)
